import { platformApi } from '../../api';
import type { PlatformRole, PlatformPermission } from '../../../types/platform';
import type { PageResponse } from '../../api';

// 平台角色查询参数（匹配后端API）
interface PlatformRoleQueryParams {
  page?: number;
  size?: number;
  current?: number;
  search?: string;
  code?: string;
  name?: string;
  status?: number; // 后端使用数字：1-正常，0-禁用
  isBuiltin?: boolean;
}

// 扩展PlatformRole类型以包含权限字段（用于创建/更新角色）
interface PlatformRoleWithPermissions extends PlatformRole {
  permissionCodes?: string[];
  sort?: number;
}

// 由于响应拦截器已经处理了数据提取，创建一个类型安全的请求方法
const request = <T>(config: any): Promise<T> => {
  return platformApi.request(config) as Promise<T>;
};

/**
 * 真实后端API实现
 */
const realPlatformRolesApi = {
  /**
   * 获取平台角色列表（分页）
   */
  getRoles: async (params?: PlatformRoleQueryParams): Promise<PageResponse<PlatformRole>> => {
    const query = {
      current: params?.page || 1,
      size: params?.size || 10,
      code: params?.search,
      name: params?.search,
      status: params?.status,
      isBuiltin: params?.isBuiltin,
      ...params
    };
    
    return request<PageResponse<PlatformRole>>({
      url: '/api/v3/platform/roles/page',
      method: 'POST',
      data: query,
    });
  },

  /**
   * 获取平台角色详情
   */
  getRole: async (roleId: string | number): Promise<PlatformRole> => {
    return request<PlatformRole>({
      url: `/api/v3/platform/roles/get/${roleId}`,
      method: 'GET',
    });
  },

  /**
   * 创建平台角色
   */
  createRole: async (roleData: Partial<PlatformRoleWithPermissions>): Promise<void> => {
    // 转换前端数据格式到后端格式
    const dto = {
      code: roleData.code,
      name: roleData.name,
      description: roleData.description,
      scope: roleData.scope,
      sort: roleData.sort || 10, // 添加排序字段，默认值为10
      status: typeof roleData.status === 'number' ? roleData.status : (roleData.status === 'active' ? 1 : 0),
      permissionCodes: roleData.permissionCodes?.join(','), // 将权限数组转换为逗号分隔的字符串
    };
    
    await request<void>({
      url: '/api/v3/platform/roles/add',
      method: 'POST',
      data: dto,
    });
  },

  /**
   * 更新平台角色
   */
  updateRole: async (roleId: string | number, roleData: Partial<PlatformRoleWithPermissions>): Promise<void> => {
    // 转换前端数据格式到后端格式
    const dto = {
      id: roleId, // 保持原始格式，避免精度丢失
      code: roleData.code,
      name: roleData.name,
      description: roleData.description,
      scope: roleData.scope,
      sort: roleData.sort, // 添加排序字段
      status: typeof roleData.status === 'number' ? roleData.status : (roleData.status === 'active' ? 1 : 0),
      permissionCodes: roleData.permissionCodes?.join(','), // 将权限数组转换为逗号分隔的字符串
    };
    
    await request<void>({
      url: '/api/v3/platform/roles/update',
      method: 'PUT',
      data: dto,
    });
  },

  /**
   * 删除平台角色
   */
  deleteRole: async (roleId: string | number): Promise<void> => {
    await request<void>({
      url: `/api/v3/platform/roles/delete/${roleId}`,
      method: 'DELETE',
    });
  },

  /**
   * 切换角色状态
   */
  toggleRoleStatus: async (roleId: string | number, status: 'active' | 'inactive'): Promise<void> => {
    const statusValue = status === 'active' ? 1 : 0;
    await request<void>({
      url: `/api/v3/platform/roles/status/${roleId}`,
      method: 'PUT',
      params: { status: statusValue },
    });
  },



  /**
   * 检查角色编码是否存在
   */
  checkRoleCodeExists: async (code: string, excludeId?: string | number): Promise<{ exists: boolean }> => {
    const params = excludeId ? { excludeId } : {};
    return request<{ exists: boolean }>({
      url: `/api/v3/platform/roles/check-code/${code}`,
      method: 'GET',
      params,
    });
  },

  /**
   * 获取所有平台权限
   */
  getAllPermissions: async (): Promise<PlatformPermission[]> => {
    return request<PlatformPermission[]>({
      url: '/api/v3/platform/permissions/all',
      method: 'GET',
    });
  },

  /**
   * 获取内置角色
   */
  getBuiltinRoles: async (): Promise<PlatformRole[]> => {
    return request<PlatformRole[]>({
      url: '/api/v3/platform/roles/builtin',
      method: 'GET',
    });
  },

  /**
   * 获取自定义角色
   */
  getCustomRoles: async (): Promise<PlatformRole[]> => {
    return request<PlatformRole[]>({
      url: '/api/v3/platform/roles/custom',
      method: 'GET',
    });
  },

  /**
   * 获取所有角色（包括内置角色和自定义角色）
   */
  getAllRoles: async (): Promise<PlatformRole[]> => {
    return request<PlatformRole[]>({
      url: '/api/v3/platform/roles/all',
      method: 'GET',
    });
  },
};





// 直接导出真实API实现
export const platformRolesApi = realPlatformRolesApi;

export default platformRolesApi;